<template>
  <div class="huanxing-tags">
    <div class="huanxing-tags_box">
      <el-tabs
        v-model="data.active"
        type="card"
        :closable="tagLen!==1"
        @tab-click="clickTab"
        @edit="handleTabsEdit"
      >
        <el-tab-pane
          :key="item.value"
          v-for="item in tagList"
          :label="item.label"
          :name="item.value"
        ></el-tab-pane>
      </el-tabs>
      <el-dropdown class="tags-dropdown">
        <el-button type="primary" size="mini">
          更多
          <el-icon class="el-icon--right">
            <ArrowDown />
          </el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="closeOthers">关闭其他</el-dropdown-item>
            <el-dropdown-item @click="closeAll">关闭全部</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>
<script>
import { defineComponent, reactive, onMounted, computed, watch } from 'vue'
import { useStore } from 'vuex'
import { ArrowDown } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
export default defineComponent({
  components: { ArrowDown },
  setup() {
    let data = reactive({
      active: '',
    })
    const store = useStore()
    const $route = useRouter()

    //首页标签导航
    const tagWel = computed(() => store.getters.tagWel)
    //全部标签导航
    const tagList = computed(() => store.getters.tagList)
    //选中标签导航
    const tag = computed(() => store.getters.tag)
    onMounted(() => {
      data.active = tag.value.value
    })
    // 监听选中标签
    watch(
      () => tag.value,
      (newValue, oldValue) => {
        data.active = tag.value.value
      }
    )
    const tagLen = computed(tagList.value.length || 0)

    const clickTab = (tab) => {
      let path = tab.props ? tab.props.name : tab.value
      $route.push({ path: path })
    }

    const handleTabsEdit = (targetName, action) => {
      if (action == 'remove') {
        if (targetName == tagWel.value.value) {
          return
        }
        const tabs = tagList.value
        let activeName = data.active
        tabs.forEach((tab, index) => {
          if (tab.value === targetName) {
            const nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              activeName = nextTab.value
              store.commit('DEL_TAG', tab)
              clickTab(nextTab)
            }
          }
        })
      }
    }

    const closeOthers = () => {
      store.commit('DEL_TAG_OTHER')
    }
    const closeAll = () => {
      store.commit('DEL_ALL_TAG')
      $route.push({ path: tagWel.value.value })
    }

    return {
      tagList,
      data,
      clickTab,
      handleTabsEdit,
      closeAll,
      closeOthers,
    }
  },
})
</script>